package com.zjj.concurrent.completableFuture;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.BiConsumer;
import java.util.function.Function;

/**
 * @author zhanglei.zjj
 * @description CompletableFuture结果处理
 * @date 2023/6/3 17:04
 */
public class WhenCompleteAndExceptionallyTest {
    public static void main(String[] args) {
        CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
            }
            if (new Random().nextInt(10) % 2 == 0) {
                int i = 12 / 0;
            }
            System.out.println("执行结束！");
            return "test";
        });

        future.whenComplete(new BiConsumer<String, Throwable>() {
            @Override
            public void accept(String t, Throwable action) {
                System.out.println(t + " 执行完成！");
            }
        });

        CompletableFuture<String> exceptionally = future.exceptionally(new Function<Throwable, String>() {
            @Override
            public String apply(Throwable t) {
                System.out.println("执行失败：" + t.getMessage());
                return "异常xxxx";
            }
        });

        // exceptionally 返回结果是一个新的CompletableFuture对象，如果发生异常，就是传入的Function函数处理结果
        // 如果没有发生异常，则和调用者 值是一样，但对象是独立的
        System.out.println(exceptionally.join());
        String resp = future.join();
        System.out.println("最终返回：" + resp);
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
